<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="菜单名称" prop="menuName">
        <el-input v-model="queryParams.menuName" placeholder="请输入菜单名称" size="small" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="菜单状态" clearable size="small">
          <el-option v-for="option in options.menuStatusOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermission="['system:menu:insert']" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" row-key="id" :data="menuList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="id" label="菜单编码" show-overflow-tooltip />
      <el-table-column prop="menuName" label="菜单名称" show-overflow-tooltip />
      <el-table-column prop="menuIcon" label="图标" align="center">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.menuIcon" />
        </template>
      </el-table-column>
      <el-table-column prop="menuType" label="菜单类型" :formatter="menuTypeFormat" show-overflow-tooltip />
      <el-table-column prop="routerPath" label="路由地址" show-overflow-tooltip />
      <el-table-column prop="componentPath" label="组件地址" show-overflow-tooltip />
      <el-table-column prop="permissions" label="权限标识" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" :formatter="statusFormat" />
      <el-table-column prop="treeSort" label="排序" width="60" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermission="['system:menu:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-hasPermission="['system:menu:insert']" size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button v-hasPermission="['system:menu:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="menuFormDialog.title" :visible.sync="menuFormDialog.visible" :close-on-click-modal="false" :before-close="resetMenuFormDialog" width="600px" append-to-body>
      <el-form ref="menuForm" :model="menuFormData" :rules="menuFormRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect v-model="menuFormData.pid" :options="options.menuOptions" :normalizer="normalizer" :show-count="true" placeholder="选择上级菜单" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="menuFormData.menuType">
                <el-radio v-for="option in options.menuTypeOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单编码" prop="id">
              <el-input v-model="menuFormData.id" placeholder="请输入菜单编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="menuFormData.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="treeSort">
              <el-input-number v-model="menuFormData.treeSort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col v-show="menuFormData.menuType !== 'BUTTON'" :span="12">
            <el-form-item label="路由地址" prop="routerPath">
              <el-input v-model="menuFormData.routerPath" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件地址" prop="componentPath">
              <el-input v-model="menuFormData.componentPath" placeholder="请输入组件地址" />
            </el-form-item>
          </el-col>
          <el-col v-show="menuFormData.menuType !== 'BUTTON'" :span="24">
            <el-form-item label="菜单图标">
              <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
                <IconSelect ref="iconSelect" @selected="handleIconSelected" />
                <el-input slot="reference" v-model="menuFormData.menuIcon" placeholder="点击选择图标" readonly>
                  <svg-icon v-if="menuFormData.menuIcon" slot="prefix" :icon-class="menuFormData.menuIcon" class="el-input__icon" style="height : 32px; width : 16px" />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col v-show="menuFormData.menuType !== 'DIRECTORY'" :span="12">
            <el-form-item label="权限标识">
              <el-input v-model="menuFormData.permissions" placeholder="请权限标识" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col v-show="menuFormData.menuType !== 'BUTTON'" :span="12">
            <el-form-item label="菜单状态">
              <el-radio-group v-model="menuFormData.status">
                <el-radio v-for="option in options.menuStatusOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-show="menuFormData.menuType !== 'BUTTON'" :span="12">
            <el-form-item label="是否显示">
              <el-radio-group v-model="menuFormData.isVisible">
                <el-radio v-for="option in options.sysYnTypeOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-show="menuFormData.menuType !== 'BUTTON'" :span="12">
            <el-form-item label="是否外链">
              <el-radio-group v-model="menuFormData.isExternalLink">
                <el-radio v-for="option in options.sysYnTypeOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-show="menuFormData.menuType === 'MENU'" :span="12">
            <el-form-item label="是否缓存">
              <el-radio-group v-model="menuFormData.isCache">
                <el-radio v-for="option in options.sysYnTypeOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmMenuFormDialog">确 定</el-button>
        <el-button @click="resetMenuFormDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MenuApi from '@/api/system/MenuApi'
import DictValueApi from '@/api/system/DictValueApi'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect'

const defaultMenuFormData = {
  id: null,
  pid: '0',
  menuName: null,
  menuIcon: '#',
  menuType: 'DIRECTORY',
  routerPath: '#',
  treeSort: 10,
  isExternalLink: '0',
  isCache: '1',
  isVisible: '1',
  status: '0'
}
export default {
  name: 'Menu',
  components: {
    Treeselect,
    IconSelect
  },
  data() {
    return {
      options: {
        sysYnTypeOptions: [],
        menuOptions: [],
        menuTypeOptions: [],
        menuStatusOptions: []
      },
      queryParams: {
        menuName: undefined,
        visible: undefined
      },
      menuList: [], // 数据列表
      menuFormDialog: {
        title: '',
        visible: false,
        type: null
      },
      menuFormData: Object.assign({}, defaultMenuFormData),
      menuFormRules: {
        id: [{ required: true, message: '菜单编码不能为空', trigger: 'blur' }],
        menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
        routerPath: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
        treeSort: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }]
      },
      loading: true,
      searchVisible: true
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      DictValueApi.list({ dictCode: 'sys_yn_type' }).then(response => {
        this.options.sysYnTypeOptions = response.data
      })
      DictValueApi.list({ dictCode: 'sys_menu_type' }).then(response => {
        this.options.menuTypeOptions = response.data
      })
      DictValueApi.list({ dictCode: 'sys_enable_disable' }).then(response => {
        this.options.menuStatusOptions = response.data
      })
    },
    handleAdd(row) {
      this.menuFormDialog.type = 'add'
      this.openMenuFormDialog(row.id)
    },
    handleRemove(row) {
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return MenuApi.remove(row.id)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      this.menuFormDialog.type = 'edit'
      this.openMenuFormDialog(row.id)
    },
    handleQuery() {
      this.loading = true
      MenuApi.list(this.queryParams).then(response => {
        this.menuList = this.$common.list2Tree(response.data, 'id')
        this.loading = false
      }, () => {
        this.loading = false
      })
      MenuApi.treeSelect().then(response => {
        this.options.menuOptions = []
        const root = { id: 0, label: '主类目', children: [] }
        root.children = response.data
        this.options.menuOptions.push(root)
      })
    },
    openMenuFormDialog(id) {
      this.menuFormDialog.visible = true
      if (this.menuFormDialog.type === 'add') {
        this.menuFormDialog.title = '菜单-添加'
        if (id) {
          this.menuFormData.pid = id
        } else {
          this.menuFormData.pid = 0
        }
      }
      if (this.menuFormDialog.type === 'edit') {
        this.menuFormDialog.title = '菜单-修改'
        MenuApi.get(id).then(response => {
          this.menuFormData = response.data
        })
      }
    },
    confirmMenuFormDialog() {
      this.$refs['menuForm'].validate(valid => {
        if (valid) {
          if (this.menuFormDialog.type === 'add') {
            MenuApi.add(this.menuFormData).then(response => {
              this.$message.success('添加成功')
              this.resetMenuFormDialog()
              this.handleQuery()
            })
          }
          if (this.menuFormDialog.type === 'edit') {
            MenuApi.edit(this.menuFormData).then(response => {
              this.$message.success('修改成功')
              this.resetMenuFormDialog()
              this.handleQuery()
            })
          }
        }
      })
    },
    resetMenuFormDialog() {
      this.menuFormDialog = {
        title: '',
        visible: false,
        type: null
      }
      this.menuFormData = Object.assign({}, defaultMenuFormData)
      this.resetForm('menuForm')
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return node
    },
    handleIconSelected(name) {
      this.menuFormData.menuIcon = name
    },
    menuTypeFormat(row) {
      return this.$common.getDictValueName(this.options.menuTypeOptions, row.menuType)
    },
    statusFormat(row) {
      if (row.menuType === 'BUTTON') {
        return ''
      }
      return this.$common.getDictValueName(this.options.menuStatusOptions, row.status)
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
